package com.haisen.service.impl;

import com.github.pagehelper.PageHelper;
import com.haisen.core.utils.DateUtil;
import com.haisen.core.utils.PageResultSet;
import com.haisen.dataobject.entity.Income;
import com.haisen.dataobject.mapper.base.IncomeMapper;
import com.haisen.dataobject.query.IncomeQuery;
import com.haisen.service.IncomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class IncomeServiceImpl implements IncomeService{

    @Autowired
    private IncomeMapper incomeMapper;

    @Override
    public void create(Income income) {
        String dateStr = DateUtil.toDateString(Calendar.getInstance().getTime());
        int r1=(int)(Math.random()*(100));//产生3个0-9的随机数
        int r2=(int)(Math.random()*(100));
        income.setBillNo(dateStr+r1+r2);
        incomeMapper.insertSelective(income);
    }

    @Override
    public void update(Income income) {
        incomeMapper.updateByPrimaryKeySelective(income);

    }

    @Override
    public void delete(Long id) {
      incomeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Income> findAll() {
        return incomeMapper.selectAll();
    }

    @Override
    public PageResultSet<Income> findByPage(IncomeQuery incomeQuery) {

        if(!StringUtils.isEmpty(incomeQuery.getOrderBy())) {
            PageHelper.orderBy(incomeQuery.getOrderBy());
        }

        Weekend<Income> example = Weekend.of(Income.class);
        WeekendCriteria<Income, Object> criteria = example.weekendCriteria();

        if (!StringUtils.isEmpty(incomeQuery.getShopName())) {
            criteria.andLike(Income::getShopName, "%" + incomeQuery.getShopName() + "%");
        }
        if(!StringUtils.isEmpty(incomeQuery.getShopNo())) {
            criteria.andLike(Income::getShopNo,"%"+incomeQuery.getShopNo()+"%");
        }

        List<Income> dtoList = new ArrayList<>();

        PageHelper.offsetPage(incomeQuery.getOffset(), incomeQuery.getLimit());
       /* userMapper.selectByExample(example).forEach(u -> {
            UserDto dto = new UserDto(u);
            dto.setOrganizationName(getOrganizationName(Long.valueOf(dto.getOrganizationId())));
            dto.setRoleNames(getRoleNames(dto.getRoleIdList()));
            dto.setGroupNames(getGroupNames(dto.getGroupIdList()));
            dtoList.add(dto);
        });*/
        dtoList = incomeMapper.selectByExample(example);
        long total = incomeMapper.selectCountByExample(example);
        PageResultSet<Income> resultSet = new PageResultSet<>();
        resultSet.setRows(dtoList);
        resultSet.setTotal(total);
        return resultSet;
    }
}
